package com.gitee.huanminabc.utils_tools.config_refresh.handler;

import com.gitee.huanminabc.utils_tools.config_refresh.core.ChangeConfigHandler;
import com.gitee.huanminabc.utils_tools.config_refresh.event.ConfigChangeEvent;
import com.gitee.huanminabc.utils_tools.config_refresh.file.ConfigFileReadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Properties;
@Component
@Slf4j
public abstract class ChangeConfigHandlerAbs  implements ChangeConfigHandler {
    private Properties oldConfig;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private ConfigFileReadFactory configFileReadFactory;
    @Override
    public void refresh() throws Exception {
        Properties newConfig = configFileReadFactory.getRead(fileType());
        if (oldConfig == null) {
            oldConfig = newConfig;
        }else{
            for (Map.Entry<Object, Object> objectObjectEntry : oldConfig.entrySet()) {
                //1. 新配置中不存在旧配置的key,这种情况不处理,不然会导致使用此配置的地方出现空指针
                if (!newConfig.containsKey(objectObjectEntry.getKey())) {
                    continue;
                }
                //检测配置是否发生变化
                if (!newConfig.get(objectObjectEntry.getKey()).equals(objectObjectEntry.getValue())) {
                    //发布事件
                    String v = newConfig.get(objectObjectEntry.getKey()).toString();
                    applicationEventPublisher.publishEvent(new ConfigChangeEvent("ChangeConfigHandlerAbs->refresh",objectObjectEntry.getKey().toString(),v));
                    oldConfig = newConfig;
                    log.info("配置发生变化,旧配置key:{},value:{},新配置key:{},value:{}",objectObjectEntry.getKey(),objectObjectEntry.getValue(),objectObjectEntry.getKey(),v);
                }
            }
        }

    }
}
